/*******************************************************************
 *
 * Copyright (C), 2021-2022, Letstrong, All rights reserved.
 *
 * Author      : 
 * Create Time : 2020-12-17
 * Version     : v0.1
 * Description : 
 *******************************************************************/
 
/*----------------------------Head file----------------------------*/
#include "pwm.h"
#include "hal_motor.h"
#include "user_config.h"
#include "hal_gpio.h"

#define HAL_MOTOR_LOG_EN		0

#if HAL_MOTOR_LOG_EN
#include "log.h"
#define HAL_MOTOR_LOG			LOG_DEBUG
#else
#define HAL_MOTOR_LOG(...)
#endif

/*----------------------------macro file---------------------------*/
#if (REMIND_TYPE == USE_MOTOR)
#define USE_PWM             0
#define MOTOR_PWM_VAL		70
#define PWM_END_VAL			100
#else
//2KHz Frequency
#define USE_PWM             1
#define MOTOR_PWM_VAL		1
#define PWM_END_VAL			8
#endif

#define MOTOR_PWM_CH_NUM	(MOTOR_PIN_NUM - GPIOB_0)

#if (MOTOR_PWM_CH_NUM > 4)
#error	"MOTOR_PWM_CH_NUM is out of range." 
#endif

/*----------------------------type define--------------------------*/

/*----------------------------var define---------------------------*/

/*-------------------------func declaration------------------------*/

/*-----------------------------------------------------------------*/

#if(USE_PWM)
static void pwm_output(uint8_t channel, uint32_t end_value, uint32_t duty)
{
	PWM_DRV_DESC motor_pwm;

	motor_pwm.channel          =   channel;
	motor_pwm.mode             =   0x11;
	motor_pwm.pre_divid        =   0;
	motor_pwm.end_value        =   end_value;
	motor_pwm.duty_cycle       =   duty;
	motor_pwm.p_Int_Handler    =   NULL;
	pwm_init(&motor_pwm);
}
#endif

void hal_motor_start(void)
{
    hal_gpio_output_cfg(MOTOR_PWR_PIN_NUM, PULL_NULL);
	hal_gpio_write(MOTOR_PWR_PIN_NUM, 1);
#if(USE_PWM)
    pwm_output(MOTOR_PWM_CH_NUM, PWM_END_VAL, MOTOR_PWM_VAL);
#else
	hal_gpio_output_cfg(MOTOR_PIN_NUM, PULL_NULL);
	hal_gpio_write(MOTOR_PIN_NUM, 1);
#endif
}

void hal_motor_stop(void)
{
#if(USE_PWM)
	pwm_disable(MOTOR_PWM_CH_NUM);
	hal_gpio_float_cfg(MOTOR_PIN_NUM, PULL_DOWN);
#else
	hal_gpio_output_cfg(MOTOR_PIN_NUM, PULL_DOWN);
	hal_gpio_write(MOTOR_PIN_NUM, 0);
#endif
    hal_gpio_output_cfg(MOTOR_PWR_PIN_NUM, PULL_DOWN);
	hal_gpio_write(MOTOR_PWR_PIN_NUM, 0);
}
